package com.kly.cashmall.utils.aliyun;

import android.content.Context;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.kly.cashmall.utils.data.TextUtil;

import java.util.UUID;

public class UploadImage {

  private static final String DOUBLE_SLASH = "//";
  private static final String SLASH = "/";
  private static final String DOT = ".";

  private static final int RESPONSE_SUCCESS = 200;

  /**
   * 同步上传图片到阿里云
   */
  public static PersistenceResponse uploadImage(Context context, AliOssTokenBean aliOssTokenBean,
                                                int maxErrorRetry, final String fileAbsPath) {

    if (aliOssTokenBean == null) {
      return null;
    }

    //*********************** 构造 OSSClient ***********************

    ClientConfiguration conf = new ClientConfiguration();
    conf.setConnectionTimeout(30 * 1000); // 连接超时，默认15秒
    conf.setSocketTimeout(30 * 1000); // socket超时，默认15秒
    conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个

    if (maxErrorRetry > 0) {
      conf.setMaxErrorRetry(maxErrorRetry); // 失败后最大重试次数，默认2次
    }

    OSSLog.disableLog();

    final String endpoint = aliOssTokenBean.baseUrl;
    final String accessKeyId = aliOssTokenBean.accessKeyId;
    final String secretKeyId = aliOssTokenBean.accessKeySecret;
    final String securityToken = aliOssTokenBean.securityToken;

    OSSCredentialProvider credentialProvider =
            new OSSStsTokenCredentialProvider(accessKeyId, secretKeyId, securityToken);

    OSSClient oss = new OSSClient(context, endpoint, credentialProvider, conf);

    //*********************** 拼接 request url ***********************

    final String bucketName = aliOssTokenBean.bucketName;
    final String objectName = aliOssTokenBean.objectName;

    final String uploadObjectKey = objectName + SLASH + UUID.randomUUID().toString();
//    final String uploadObjectKey = objectName + fileAbsPath.substring(fileAbsPath.lastIndexOf(SLASH));
    final String[] splitUrlParts = endpoint.split(DOUBLE_SLASH);

    String requestUrlSB = splitUrlParts[0]
            + DOUBLE_SLASH
            + bucketName
            + DOT
            + splitUrlParts[1]
            + SLASH
            + uploadObjectKey;
    String cloudUrl =
            putObjectFromLocalFile(oss, bucketName, uploadObjectKey, fileAbsPath) ? requestUrlSB : null;

    PersistenceResponse response = new PersistenceResponse();
    response.cloudUrl = cloudUrl;
    response.success = !TextUtil.isEmpty(cloudUrl);
    response.fileAbsPath = fileAbsPath;
    return response;
  }

  // 从本地文件上传，采用阻塞的同步接口
  private static boolean putObjectFromLocalFile(OSS client, String bucketName, String ObjectName,
                                                String uploadFilePath) {
    // 构造上传请求
    PutObjectRequest put = new PutObjectRequest(bucketName, ObjectName, uploadFilePath);

    try {
      PutObjectResult putResult = client.putObject(put);
      return putResult != null && putResult.getStatusCode() == RESPONSE_SUCCESS;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
}
